package net.lab1024.sa.admin.aspect;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 上游api接口的切面
 */
@Slf4j
@Aspect
@Component
public class UpstreamApiAspect {

    /** 匹配BaseApi类或者所有子类实例，并且必须是public修饰的方法，任意方法名，任意参数 */
    @Before("target(net.lab1024.sa.admin.module.upstream.api.BaseApi) && execution(* *(..))")
    public void before(JoinPoint joinPoint) {
        Class<?> clazz = joinPoint.getTarget().getClass();
        Method method = null;
        try {
            method = clazz.getDeclaredMethod("refresh");
        } catch (NoSuchMethodException e) {
            // 没有refresh只打印不抛异常
            log.error("{}中没有刷新上游参数配置的方法！", clazz.getSimpleName());
            return;
        }
        // 绕过非public修饰权限
        method.setAccessible(true);
        try {
            method.invoke(joinPoint.getTarget());
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("{}调用刷新上游参数配置的方法时异常！", clazz.getSimpleName());
            log.error(e.getMessage());
            if (e instanceof IllegalAccessException) {
                throw new BusinessException("非法入参！");
            } else {
                throw new BusinessException(((InvocationTargetException) e).getTargetException().getMessage());
            }
        }
    }
}
